package cn.cdeden.aiqa.service.impl;

import cn.cdeden.aiqa.domain.ExpertApp;
import cn.cdeden.aiqa.domain.WikiApp;
import cn.cdeden.aiqa.domain.WikiAppPerm;
import cn.cdeden.aiqa.domain.vo.ExpertAppVo;
import cn.cdeden.aiqa.domain.vo.UserMessageVo;
import cn.cdeden.aiqa.mapper.ExpertAppMapper;
import cn.cdeden.aiqa.service.ExpertAppService;
import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.StringUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.core.page.PageQuery;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.system.api.RemoteDifyService;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.bo.RemoteDifyKnowledgeBaseBo;
import cn.cdeden.system.api.domain.vo.RemoteDifyKnowledgeBaseCreateVo;
import cn.cdeden.system.api.domain.vo.RemoteUserVo;
import cn.cdeden.system.api.model.LoginUser;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ExpertAppServiceImpl implements ExpertAppService {

    private final ExpertAppMapper expertAppMapper;

    @DubboReference(check = false)
    private final RemoteDifyService remoteDifyService;

    @DubboReference(check = false)
    private final RemoteUserService remoteUserService;

    @Override
    public ExpertApp createExpertApp(ExpertApp expertApp) {
//        LoginUser loginUser = LoginHelper.getLoginUser();
        //创建知识库
        RemoteDifyKnowledgeBaseBo bo = new RemoteDifyKnowledgeBaseBo();
        bo.setName(expertApp.getWikiNames());
        bo.setIndexing_technique("high_quality");
        bo.setPermission("all_team_members");
        RemoteDifyKnowledgeBaseCreateVo remoteDifyKnowledgeBaseCreateVo = remoteDifyService.create(bo);

        expertApp.setWikiIds(remoteDifyKnowledgeBaseCreateVo.getId());
//        expertApp.setUserId(loginUser.getUserId());
        expertAppMapper.insert(expertApp);
        return expertApp;
    }

    @Override
    public void updateExpertApp(ExpertApp expertApp) {
        //判断唯一性
        List<ExpertApp> expertApps = expertAppMapper.selectList(new LambdaQueryWrapper<ExpertApp>().eq(ExpertApp::getUserId, expertApp.getUserId()).ne(ExpertApp::getId, expertApp.getId()));
//        List<ExpertApp> collect = expertApps.stream().filter(expertApp1 -> expertApp1.getUserId() != expertApp.getUserId()).collect(Collectors.toList());
        if (!expertApps.isEmpty()) {
            throw new RuntimeException("选择的人员已经关联过专家知识库了");
        }
        expertAppMapper.updateById(expertApp);
    }

    @Override
    public void deleteExpertApps(List<Long> ids) {
        expertAppMapper.deleteByIds(ids);
//        expertAppMapper.delete(new LambdaQueryWrapper<ExpertApp>()
//            .in(ExpertApp::getAppId, ids));
    }

    @Override
    public TableDataInfo<ExpertAppVo> getAllExpertApps(String appName,String wikiNames, String userName, PageQuery pageQuery) {
        //通过模糊查询，查询出符合的用户的id
        List<Long> userIds = null;
        if (StringUtils.isNotBlank(userName)) {
            userIds = remoteUserService.likeUserNames(userName);
        }


        LambdaQueryWrapper<ExpertApp> lqw = buildQueryWrapper(appName, wikiNames, userIds);
        Page<ExpertApp> result = expertAppMapper.selectPage(pageQuery.build(), lqw);
        //处理拼接所属人员名称
        List<ExpertApp> records = result.getRecords();
        List<ExpertAppVo> convert = MapstructUtils.convert(records, ExpertAppVo.class);
        List<Long> collect = records.stream().map(ExpertApp::getUserId).collect(Collectors.toList());
        List<RemoteUserVo> remoteUserVos = null;
        Page<ExpertAppVo> newExpertAppPage = new Page<ExpertAppVo>();
        if (!ObjectUtil.isEmpty(collect)) {
            remoteUserVos = remoteUserService.selectUserAllByUserId(collect);
            Map<Long, String> userNameMap = remoteUserVos.stream().collect(Collectors.toMap(RemoteUserVo::getUserId, RemoteUserVo::getNickName));

            convert.forEach( v -> {
                v.setUserName(userNameMap.get(v.getUserId()));
            });
        }


        newExpertAppPage.setRecords(convert);
        newExpertAppPage.setCurrent(result.getCurrent());
        newExpertAppPage.setPages(result.getPages());
        newExpertAppPage.setSize(result.getSize());
        newExpertAppPage.setTotal(result.getTotal());


        return TableDataInfo.build(newExpertAppPage);
    }

    @Override
    public boolean crCount(Long appId) {
        ExpertApp expertApp = expertAppMapper.selectById(appId);

        Long rCount = expertApp.getRCount();
        expertApp.setRCount(++rCount);

        return expertAppMapper.updateById(expertApp) > 0;
    }

    @Override
    public ExpertApp getRemoteExpertApp() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        ExpertApp expertApp = expertAppMapper.selectOne(new LambdaQueryWrapper<ExpertApp>()
            .eq(ExpertApp::getUserId, loginUser.getUserId()));
        return expertApp;
    }

    @Override
    public Long getByUserId(Long userId) {
        return expertAppMapper.selectCount(new LambdaQueryWrapper<ExpertApp>()
            .eq(ExpertApp::getUserId, userId));
    }

    @Override
    public ExpertApp getDataBaseIdByUserId(Long userId) {
        return expertAppMapper.selectOne(new LambdaQueryWrapper<ExpertApp>()
            .eq(ExpertApp::getUserId, userId));
    }

    @Override
    public UserMessageVo getUserMessage(Long id) {
        ExpertApp expertApp = expertAppMapper.selectOne(new LambdaQueryWrapper<ExpertApp>().eq(ExpertApp::getId, id));
        if (expertApp.getUserId() != null) {
            RemoteUserVo loginUserByUserId = remoteUserService.selectUserByUserId(expertApp.getUserId());
            UserMessageVo userMessageVo = new UserMessageVo();
            userMessageVo.setUserId(loginUserByUserId.getUserId());
            userMessageVo.setUserName(loginUserByUserId.getNickName());
            return userMessageVo;
        }
        return new UserMessageVo();
    }

    @Override
    public List<ExpertApp> getAuthorizedApps(int open) {
        if (open == 1) {
            return expertAppMapper.selectList(new LambdaQueryWrapper<ExpertApp>().eq(ExpertApp::getOpen, 1));
        }
        LoginUser loginUser = LoginHelper.getLoginUser();
        return expertAppMapper.selectList(new LambdaQueryWrapper<ExpertApp>().eq(ExpertApp::getUserId, loginUser.getUserId()));
    }

    @Override
    public ExpertApp getById(Long id) {
        return expertAppMapper.selectById(id);
    }


    private LambdaQueryWrapper<ExpertApp> buildQueryWrapper(String appName, String wikiNames, List<Long> userIds) {
        LambdaQueryWrapper<ExpertApp> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(wikiNames), ExpertApp::getWikiNames, wikiNames);
        lqw.in(userIds != null, ExpertApp::getUserId, userIds);
        return lqw;
    }

}
